package com.thread.sync.sync01;

public class MyThread02 {
    /**
     * 如果synchronized修饰在普通方法上,多个线程多个锁情况下,线程之间互无关系,可任意执行自己对象的锁
     * 在static方法上修饰synchronized表示锁定class类.多个线程都是相同的锁
     * 取得的锁都是对象锁,哪个线程先执行代码,哪个线程就持有该方法所属的对象锁,其他对象无法执行
     */
    private static int num = 0;

    private static synchronized void printNum(String tag) {
        try {
            if (tag.equals("a")) {
                num = 100;
                System.out.println("tag a,num set over!");
                Thread.sleep(1000);//休眠1秒
            } else {
                num = 200;
                System.out.println("tag b,set num over!");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("tag :" + tag + ", num=" + num);
    }

    public static void main(String[] args) {
        MyThread02 my1 = new MyThread02();
        MyThread02 my2 = new MyThread02();
        //匿名内部类方式启动线程
        new Thread(() -> my1.printNum("a")).start();
        new Thread(() -> my2.printNum("b")).start();
    }

}
